package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-09-23
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    @Cacheable("dict")
    public List<Dict> getDictListByParentId(Long pid) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",pid);
        List<Dict> dictList = baseMapper.selectList(queryWrapper);

        for (Dict dict : dictList) {
            Boolean flag = hasChildren(dict.getId());
            dict.setHasChildren(flag);
        }
        return dictList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //response.setContentType("application/vnd.ms-excel");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            //让浏览器打开下载页面
            response.setHeader("Content-disposition","attachment;filename="+fileName);

            //准备数据
            List<Dict> dictList = baseMapper.selectList(null);
            ArrayList<DictEeVo> dictVolist = new ArrayList<>();
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictEeVo);
                dictVolist.add(dictEeVo);
            }

            //导入Excel
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(dictVolist);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importData(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
    }

    @Override
    public Dict getNameByParentCodeAndValue(String parentCode, String value) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("value",Long.parseLong(value));
        if(!StringUtils.isEmpty(parentCode)){
            QueryWrapper<Dict> query = new QueryWrapper<>();
            query.eq("dict_code",parentCode);
            Dict dict = baseMapper.selectOne(query);
            queryWrapper.eq("parent_id",dict.getId());
        }
        return baseMapper.selectOne(queryWrapper);
    }


    private Boolean hasChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
